<script setup lang='ts' name="assign-roles">
import type { PlusColumn } from 'plus-pro-components'

import { resetPwd } from '@fl/api/iam-api'
import { SubmitBtn } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import type {
    TabsPaneContext,
    TransferDirection,
    TransferKey,
    renderContent,
} from 'element-plus'
import { getJointAppKey, getJointToken } from '@fl/logics/jointAuth'
import { ref } from 'vue'
import { useSessionStorage } from '@vueuse/core'
import { bindUserAreaRole, bindUserPermissionRole, getAreaRoleList, getCompanyByLoginUser, getRoleList, getStaffByIam, getStaffById, getUserInfo } from '@fl/api/joint-api'

const emits = defineEmits(['confirm'])
const user = defineModel<{
    extend1: string
    extend2: string
    userName: string
    accountUuid: string
    id: string
}>('user', { required: true })
const visible = defineModel<boolean>('visible', { required: true })
console.log('🚀 ~ user:', user)

const title = ref('分配角色')

const jointCard = {
    name: '联合运营',
    appKey: getJointAppKey(),
}
const cardList = ref<{
    name: string
    appKey: any
}[]>([])

const companyId = ref('')
async function init() {
    const res = await getAreaRoleList()
    console.log('🚀 ~ watch ~ res?.records:', res?.records)
    areaRolesList.value = res?.records || []
    console.log('🚀 ~ AreaRoles ~ AreaRoles:', areaRolesList.value)

    const companyDetailStorage = useSessionStorage('companyDetail', null)
    let companyDetail = companyDetailStorage.value ? JSON.parse(companyDetailStorage.value) : null
    console.log('🚀 ~ getListData ~ companyDetail:', companyDetail)

    if (!companyDetail) {
        companyDetail = await getCompanyByLoginUser()
        companyId.value = companyDetail.id
        useSessionStorage('companyId', companyDetail.id)
        useSessionStorage('companyDetail', companyDetail)
    }
    const companyCard = companyDetail?.companyCardAssociationList.map(card => ({
        name: card.cardName,
        appKey: card.appKey,
    }))
    cardList.value = [jointCard, ...companyCard]
    console.log('🚀 ~ init ~ cardList.value :', cardList.value)
}

const promiseRolesList = ref<any[]>([])
const checkedPromiseRoles = ref<any[]>([])

const areaRolesList = ref<any[]>([])
const checkedAreaRoles = ref<any[]>([])

watchEffect(() => {
    if (user.value.accountUuid) {
        console.log('🚀 ~ watchEffect ~ user.value:', user.value)

        // 字符串转数组
        if (user.value.extend1) {
            checkedAreaRoles.value = user.value.extend1?.split(',')
        }
        if (user.value.extend2) {
            checkedPromiseRoles.value = user.value.extend2?.split(',')?.map(id => Number(id))
        }
    }
})

watch(() => checkedPromiseRoles.value, (val) => {
    console.log('🚀 ~ checkedPromiseRoles.value ~ val:', val)
})

watch(() => cardList.value, async (val) => {
   
    const promiseRoles = await Promise.allSettled(val.map((item) => {
        return getRoleList({ appKey: item.appKey })
    }))

    promiseRolesList.value = promiseRoles.map((item) => {
        if (item.status === 'fulfilled') {
            return item.value.list
        }

        return []
    })

    // console.log('🚀 ~ promiseRoles ~ promiseRoles:', promiseRolesList.value)
})
init()

const { isPending, mutateAsync: runBindUserPermissionRole } = useMutation({
    mutationFn: data => bindUserPermissionRole(data),
    onSuccess: async (data) => {
        // console.log('🚀 ~ bindUserPermissionRole ~ data:', data)
        ElMessage.success('保存成功')
        setTimeout(() => {
            visible.value = false
            emits('confirm')
        }, 1000)
    },
})

const { isPending: bindLoading, mutateAsync: runBindUserAreaRole } = useMutation({
    mutationFn: data => bindUserAreaRole(data),
    onSuccess: async (data) => {
        console.log('🚀 ~ bindUserAreaRole ~ data:', data)
        ElMessage.success('保存成功')

        setTimeout(() => {
            visible.value = false
            emits('confirm')
        }, 1000)
    },
})
// 提交
async function submit() {
    if (activeName.value === 'permission') {
        if (checkedPromiseRoles.value.length === 0) {
            return ElMessage.error('请选择权限角色')
        }
        const params = {
            accountUuid: user.value.accountUuid,
            appRoleIds: checkedPromiseRoles.value,
        }
        console.log('🚀 ~ submit ~ params:', params)
        runBindUserPermissionRole([params])
    }
    else {
        if (checkedAreaRoles.value.length === 0) {
            return ElMessage.error('请选择区域角色')
        }
        const params = checkedAreaRoles.value.map((roleId) => {
            return {
                staff: { ...user.value },
                areaRole: { id: roleId },
            }
        })

        console.log('🚀 ~ submit ~ params:', params)
        runBindUserAreaRole(params)
    }
}

function cancel() {
    visible.value = false
}

function reset() {
    user.value.accountUuid = ''
    checkedPromiseRoles.value = []
    checkedAreaRoles.value = []
}

const activeName = ref('permission')

function handleClick(tab: TabsPaneContext, event: Event) {
    // if(){}
    // console.log(tab, event)
}
</script>

<template>
    <PlusDialog v-model="visible"
                :title="title"
                width="800"
                close-on-press-escape
                :has-footer="false"
                @cancel="cancel"
                @closed="reset"
    >
        <div class="m-auto">
            <el-tabs v-model="activeName"
                     class="demo-tabs"
                     @tab-click="handleClick"
            >
                <el-tab-pane label="权限角色"
                             name="permission"
                >
                    <div class="mt20">
                        <div v-for="(item, idx) in cardList"
                             :key="item.appKey"
                        >
                            <div class="mb6">
                                {{ item.name }}
                            </div>

                            <div v-if="promiseRolesList?.[idx] && promiseRolesList?.[idx].length > 0"
                                 class="pl-20 mb20"
                            >
                                <el-checkbox-group v-model="checkedPromiseRoles"
                                                   privileges
                                >
                                    <el-checkbox v-for="(promiseRole) in promiseRolesList?.[idx]"
                                                 :key="promiseRole.id"
                                                 :value="promiseRole.id"
                                                 :label="promiseRole.name"
                                    >
                                        {{ promiseRole.name }}
                                    </el-checkbox>
                                </el-checkbox-group>
                            </div>

                            <div v-else
                                 class="pl-20 mb20 color-#999"
                            >
                                暂无数据
                            </div>
                        </div>
                    </div>
                </el-tab-pane>

                <el-tab-pane label="区域角色"
                             name="area"
                >
                    <div class="mt20">
                        <div v-if="areaRolesList?.length > 0"
                             class="pl-20 mb20"
                        >
                            <el-checkbox-group v-model="checkedAreaRoles"
                                               privileges
                            >
                                <el-checkbox v-for="(areaRole) in areaRolesList"
                                             :key="areaRole.id"
                                             :value="areaRole.id"
                                             :label="areaRole.areaRoleName"
                                >
                                    {{ areaRole.areaRoleName }}
                                </el-checkbox>
                            </el-checkbox-group>
                        </div>

                        <div v-else
                             class="pl-20 mb20 color-#999"
                        >
                            暂无数据
                        </div>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>

        <div class="mx-auto mt20 flex justify-center">
            <el-button @click="cancel">
                取消
            </el-button>

            <SubmitBtn type="primary"
                       :loading="isPending || bindLoading"
                       @click="submit"
            >
                提交
            </SubmitBtn>
        </div>
    </PlusDialog>
</template>
